package main

import "strings"

type Node struct {
	Path  string `json:"path"`
	Name  string `json:"name,omitempty"`
	Type  string `json:"type"`
	Mtime int64  `json:"mtime,omitempty"`
	Size  int    `json:"size,omitempty"`
	Items []Node `json:"items,omitempty"`
}

func buildTree(root *Node, file FileEntry) {
	parts := strings.Split(file.Path, "/")
	current := root
	for i, part := range parts {
		if i == len(parts)-1 {
			// This is the file node
			name := part
			if strings.HasSuffix(part, ".md") {
				name = part[:len(part)-3]
			}
			fileNode := Node{
				Path:  file.Path,
				Name:  name,
				Type:  "file",
				Mtime: file.Mtime,
				Size:  file.Size,
			}
			current.Items = append(current.Items, fileNode)
		} else {
			// This is a directory node
			dirPath := strings.Join(parts[:i+1], "/") + "/"
			var dirNode *Node
			for j := range current.Items {
				if current.Items[j].Path == dirPath {
					dirNode = &current.Items[j]
					break
				}
			}
			if dirNode == nil {
				dirNode = &Node{Path: dirPath, Name: part, Type: "dir"}
				current.Items = append(current.Items, *dirNode)
				// Need to point to the newly added directory
				dirNode = &current.Items[len(current.Items)-1]
			}
			current = dirNode
		}
	}
}
